<template>
  <div class="follw-template">
    <zsearch  v-loading="loading">
    <template #title>
      <span>模板管理</span>
    </template>
      <template #btns>
        <el-button class="btn-1" @click="hanledOAdd">新增</el-button>
        <el-button class="btn-1" @click="req">刷新</el-button>
      </template>
      <template #table>
        <el-table :data="tableData" style="width: 100%" :header-cell-style="{background:'#11b9d0', color:'#fff'}" row-key="id">
          <el-table-column label="序号" type="index" width="100" />
          <el-table-column prop="createTime" label="创建时间"  />
          <el-table-column prop="name" label="模板名称"  />
          <el-table-column prop="createType" label="随访创建类型"  />
          <el-table-column prop="status" label="是否启用" >
            <template #default="scope">
              <el-switch
                  v-model="scope.row.status"
                  size="large"
                  :width="80"
                  inline-prompt
                  active-text="开启"
                  inactive-text="关闭"
                  @change="switchChange($event, scope.row)"

                />
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" >
            <template #default="scoped">
              <el-button type="text" size="small" @click="hanledOpen(scoped.row)">编 辑</el-button>
              <el-button type="text" size="small" @click="handleDelete(scoped.row)">删 除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <template #page>
        <zpage 
            :currentPage="current" 
            :total="total"
            :pageSize="size"
            @handleSizeChange="handleSizeChange" 
            @handleCurrentChange="handleCurrentChange"
        ></zpage>
      </template>
    </zsearch>
  </div>


  <zdrawer size="45%" @handleClose="drawerClose" :title="Title" v-model="ShowDrawer" >
    <template #body>
      <div class="plan-content">
        <div class="one-content">
          <div class="label">模板名称</div>
          <el-input v-model="name"  placeholder="请输入模板名称" />
        </div>
        <div class="one-content">
          <div >随访创建类型</div>
          <el-select v-model="createType" class="w-180"  filterable placeholder="请选择">
            <el-option
              v-for="item in createTypeOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </div>
        <div class="one-content">
          <div >随访创建时间类型</div>
          <el-select v-model="createTimeType" class="w-180"  filterable placeholder="请选择">
            <el-option
              v-for="item in createTimeTypeOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </div>
      </div>
      <el-row>
        <div class="plan" v-for="(item, index) in plan" :key="index">
              <header class="plan-head">
                <div class="head-left">
                  <span>计划{{index + 1}}</span>
                  <span>就诊后{{item.timeNumber}}{{ item.timeType || '天'}}</span>
                </div>
                <div class="head-right">
                  <span @click="delPlan(index)">删除计划</span>
                </div>
              </header>
              <div class="plan-content">
                <div class="one-content">
                  <div class="label">计划时间</div>
                        <el-date-picker
                            style="width: 30px"
                            :clearable="false"
                            type="date"
                            @change="handleChangeDate($event, index)"
                            >
                        </el-date-picker>
                        <el-input v-model="item.timeNumber" style="width: 50px" />
                        <div class="type-btns">
                          <div v-for="(time) in TimeType" :key="time.id"
                            :class="{'active': item.timeType === time.name}" 
                            @click="setDateType(time.id, index)"
                          >{{time.name}}</div>
                        </div>
                      <span>后</span>
                </div>
                
                <div class="one-content">
                  <div class="label">随访医生</div>
                  <el-select v-model="item.doctorType" class="w-180" filterable  placeholder="请选择">
                    <el-option
                      v-for="item in doctorTypeOptions"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                  <template v-if="item.doctorType === '其他医生'">
                    <el-select v-model="item.doctorId" class="w-180" filterable  placeholder="请选择">
                      <el-option
                        v-for="item in doctorOptions"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                      </el-option>
                    </el-select>
                  </template>
                  
                </div>
                <div class="one-content">
                  <div class="label">随访项目</div>
                  <el-select v-model="item.accessItem" clearable filterable  class="w-180"  placeholder="请选择">
                    <el-option
                      v-for="item in optionOrderDetails"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </div>

                <div class="one-content">
                  <div class="label">随访人员</div>
                  <el-select v-model="item.dealUserType" class="w-180"  filterable placeholder="请选择">
                    <el-option
                      v-for="item in dealUserTypeOptions"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                  <template v-if="item.dealUserType === '其他人员'">
                    <el-select v-model="item.dealUserId" class="w-180"  filterable placeholder="请选择">
                      <el-option
                        v-for="item in dealUserOptions"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                      </el-option>
                    </el-select>
                  </template>
                </div>
                

                <div class="one-content" >
                  <div class="label">随访内容</div>
                  <div>
                    <el-select
                      v-model="item.planContentType"
                      @change="handleSelectChange($event, index)" 
                      placeholder="请选择"
                      filterable
                      >
                      <el-option
                        v-for="item in optionList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                      </el-option>
                    </el-select>
                    <el-input
                      type="textarea"
                      :rows="2"
                      class="content-input"
                      placeholder="请输入内容"
                      v-model="item.planContent">
                    </el-input>
                  </div>
                  
                </div>


              </div>
          </div>
        <div class="btns">
          <el-button class="btn-9"  @click="addPlan">新增计划</el-button>
        </div>
      </el-row>
    </template>
    <template #footer>
      <el-button class="btn-2" @click="drawer">取消</el-button>
      <el-button class="btn-1" @click="save(Title)">保存</el-button>
    </template>
  </zdrawer>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs, onMounted, nextTick } from 'vue'
import ztable from '@components/Table/index.vue'
import zpage from '@components/pagination/pagination.vue'
import zsearch from '@components/search/search.vue'
import zdrawer from "@components/drawer/drawer.vue"

import { 
  getPageApi, getCreateTypeAPI, getDealUserTypeAPI, 
  getDoctorTypeAPI, getAccessFollowItemAPI, getAccessFollowContentAPI, 
  getTimeTypeAPI, addModelAPi, getModelDetailAPi,updateModelAPi, delModelAPi, updateStatusAPi, moveModelByIdsAPi,getCreateTimeTypeAPI } from '../../../api/follow'
import { getUserListsAPi, getDoctorUserByStatusAPi } from '../../../api/common'

import { getNowDate } from '../../../utils/nowDate'
import {Option} from "../../../types"

import { ElMessage, ElMessageBox } from 'element-plus'
import Sortable from 'sortablejs'

export default defineComponent({
  name: 'FollowTemplate',
  components: {
    ztable,
    zpage,
    zsearch,
    zdrawer
  },
  setup() {
    const state = reactive({
      loading: false,
      date: '',
      tableData: [],
      current: 1,
      total: 0,
      size: 10,

      ShowDrawer: false,
      Title: '新增随访模板',
      TimeType: [] as Option[],
      doctorOptions:[] as Option[],
      doctorTypeOptions:[] as Option[],
      dealUserOptions: [] as Option[],
      dealUserTypeOptions: [] as Option[],
      
      optionList: <Option[]>[],
      optionOrderDetails: <Option[]>[],

      createTypeOptions: [] as Option[],
      createTimeTypeOptions: [] as Option[]

    })

    // 随访模板列表
    const req = async() => {
      state.loading = true
      let params = {
        current: state.current,
        size: state.size,
      }
      let res:any = await getPageApi(params)
      state.tableData = res.data.records
      state.total = res.data.total
      state.current = res.data.current
      
      state.tableData.forEach((i:any) => {
        i.status = i.status === '开启' ? true : false
      })
      console.log(res)
      state.loading = false
    }

    // 随访创建类型
    const getCreateType = async() => {
      let res:any = await getCreateTypeAPI({})
      console.log(res)
      state.createTypeOptions = res.data
      data.createType = res.data && res.data[0].id
    }

    // 随访创建时间类型
    const getCreateTimeType = async() => {
      let res:any = await getCreateTimeTypeAPI({})
      console.log(res)
      state.createTimeTypeOptions = res.data
      data.createTimeType = res.data && res.data[0].id
    }
    // 随访模版医生类型
    const getDoctorType = async() => {
      let res:any = await getDoctorTypeAPI({})
      console.log(res)
      state.doctorTypeOptions = res.data
    }
    // 获取医生下拉 
    const getDoctorUserByStatus = async() => {
      let res:any = await getDoctorUserByStatusAPi({})
      console.log(res)
      state.doctorOptions = res.data
    }
    // 随访模板人员类型
    const getDealUserType = async () => {
      let res:any = await getDealUserTypeAPI({})
      state.dealUserTypeOptions = res.data
    }

    // 所有人员下拉
    const getUserLists = async() => {
      let res:any = await getUserListsAPi({})
      state.dealUserOptions = res.data
    }

    // 随访项目
    const getAccessFollowItem = async() => {
      let res:any = await getAccessFollowItemAPI({})
      state.optionOrderDetails = res.data
    }

    // 随访内容
    const getAccessFollowContent = async() => {
      let res:any = await getAccessFollowContentAPI({})
      state.optionList = res.data
    }

    // 随访时间类型
    const getTimeType = async() => {
      let res: any = await getTimeTypeAPI({})
      state.TimeType = res.data
    }

    // 获取随访单个项目信息
    const getModelDetail = async(id: number) => {
      let res:any = await getModelDetailAPi({}, id)
      console.log(res)
      let result = res.data

      data.name = result.name
      data.createType = result.createType
      data.createTimeType = result.createTimeType


      planList.plan = []
      result.details.forEach((item:any) => {
        planList.plan.push({
          timeNumber: item.timeNumber,
          timeType: item.timeType,
          accessItem: Number(item.accessItem) as any,
          planContentType: item.planContentType,
          planContent: item.planContent,
          doctorType: item.doctorType,
          doctorId: item.doctorId,
          dealUserType: item.dealUserType,
          dealUserId: item.dealUserId
        })
      })
    }

    onMounted(() => {
      drap()
      req()
      getCreateType()
      getCreateTimeType()
      getDoctorType()
      getTimeType()
      getDoctorUserByStatus()
      getAccessFollowItem()
      getDealUserType()
      getAccessFollowContent()
      getUserLists()
    })

    const drap = () => {
      console.log('拖动')
      let el: any = document.querySelector('.el-table__body-wrapper table tbody')

      Sortable.create(el, {
        ghostClass: "sortable-ghost",
        chosenClass: "sortable-chosen",
        dragClass: "sortable-drag",
        animation: 1000,
        async onEnd(e: any) {
        
          let currentRow = state.tableData.splice(e.oldIndex, 1)[0]
          
          await nextTick()
          state.tableData.splice(e.newIndex, 0, currentRow)

          console.log(e, currentRow, state.tableData)
          let ids = state.tableData.map((item:any) => {
            return item.id
          })
          
          moveModelByIds(ids)
        }
      })
      }
    const moveModelByIds = async(ids: number[]) => {
      let res:any = await moveModelByIdsAPi({ids})
      if(res.code === 0) {
        req()
      } else {
        ElMessage.error('移动模板' + res.msg)
      }

    }

    let data = reactive({
      id: null,
      name: '',
      createType: '',
      createTimeType: ''
    })

    const handleSizeChange = (val: number) => {
      state.size = val
      req()
    }

    const handleCurrentChange = (val: number) => {
      state.current = val
      req()
    }
    const hanledOAdd = () => {
      state.Title = '新增随访模板'
      
      state.ShowDrawer = true
      reset()
    }
    const  hanledOpen = (rowData: any) => {
      state.Title = '编辑随访模板'
      
      state.ShowDrawer = true

      data.id = rowData.id
      getModelDetail(rowData.id)

      console.log(rowData)
    }

    const switchChange = async(v:boolean, rowData: any) => {
      let { id } = rowData
      let status = v ? '开启' : '关闭'

      let res: any = await updateStatusAPi({id, status})
      if(res.code === 0) {
        ElMessage.success('修改模板状态成功')
        req()
      } else {
        ElMessage.error('修改模板状态' + res.msg)
      }
      console.log(v, id)
    }

    const handleDelete = (rowData:any) => {
      let { id } = rowData;

      ElMessageBox.confirm(`此操作将删除改模板, 是否继续?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          delModel(id)
        }).catch(() => {
          ElMessage({
            type: 'info',
            message: '已取消删除',
          });
        })
    }

    const delModel = async (id: number) => {
      let res:any = await delModelAPi({}, id)

      if(res.code === 0) {
        ElMessage.success('删除模板成功')
        req()
      } else {
        ElMessage.error('删除模板' + res.msg)
      }
    }


    const reset = () => {
      data.name = ''

      planList.plan[0].timeNumber = 0
      planList.plan[0].timeType = '天'
      planList.plan[0].accessItem = null
      planList.plan[0].planContentType = ''
      planList.plan[0].planContent = ''
      planList.plan[0].doctorType = '就诊医生'
      planList.plan[0].doctorId = ''
      planList.plan[0].dealUserType = '其他人员'
      planList.plan[0].dealUserId = ''
    }

    const drawerClose = () => {
      ElMessageBox.confirm(`此操作将关闭窗口, 是否继续?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          state.ShowDrawer = false
        }).catch(() => {
          ElMessage({
            type: 'info',
            message: '已取消删除',
          });
        })
      
    }

    const drawer = () => {
      state.ShowDrawer = false
    }

    const planList = reactive({
      plan:[
        {
          timeNumber: 0,
          timeType: '天',
          accessItem: null,
          planContentType: '',
          planContent: '',
          doctorType: '就诊医生',
          doctorId: '',
          dealUserType: '其他人员',
          dealUserId: ''
        }
      ],
    })

    // 随访 新增计划
    const addPlan = () => {
      planList.plan.push({
        timeNumber: 0,
        timeType: '天',
        accessItem: null,
        planContentType: '',
        planContent: '',
        doctorType: '就诊医生',
        doctorId: '',
        dealUserType: '其他人员',
        dealUserId: ''
      })
    }
    const delPlan = (index: number) => {
      planList.plan.splice(index, 1)
    }

    const handleChangeDate = (e: Date, index = -1) => {
        
    }

    const handleSelectChange = (v: string, index: number) => {
        planList.plan[index].planContent = v
    }

    const setDateType = (type: any, index: number) => {
      console.log(type, index, '设置')
      planList.plan[index].timeType = type
    }

    const save = (type: string) => {
      if(type === '新增随访模板') {
        addTemplate()
      } else if(type === '编辑随访模板') {
        editTemplate()
      }
    }


    const addTemplate = async() => {
      let params = {
        name: data.name,
        createType: data.createType,
        createTimeType: data.createTimeType,
        details: planList.plan
      }
      let res:any = await addModelAPi(params)
      console.log(res)
      if(res.code === 0) {
        ElMessage.success('添加模板成功')
        reset()
        drawer()
        req()
      } else {
        ElMessage.error('添加模板' + res.msg)
      }
    }

    const editTemplate = async() => {
      let params = {
        id: data.id,
        name: data.name,
        createType: data.createType,
        createTimeType: data.createTimeType,
        details: planList.plan
      }

      let res:any = await updateModelAPi(params)
      if(res.code === 0) {
        ElMessage.success('修改模板成功')
        reset()
        drawer()
        req()
      } else {
        ElMessage.error('修改模板' + res.msg)
      }
    }

    return {
      ...toRefs(state),
      handleSizeChange,
      handleCurrentChange,
      req,

      hanledOAdd,
      handleDelete,
      hanledOpen,
      drawerClose,
      drawer,
      save,

      ...toRefs(data),
      ...toRefs(planList),
      switchChange,
      addPlan,
      delPlan,
      handleChangeDate,
      handleSelectChange,
      setDateType
    }
  }
})
</script>

<style lang="scss"  scoped>
.drawer-content {
  padding: 0;
}
.el-row {
  margin: 10px;
}
.follw-template {
  .head-search {
    padding: 10px 20px;
  }
}

.plan {
  // height: 160px;
  border: 1px solid $mainColor;
  border-radius: $radius-1;
  margin-bottom: 10px;
  box-sizing: border-box;
  margin-top: 20px;
  .plan-head {
    padding: 0 10px 0 10px;
    height: 40px;
    line-height: 40px;
    border-bottom: 1px solid $mainColor;
    display: flex;
    font-size: $fontSize;
    background: $a2-Color;
    .head-left {
      & > span:first-child {
        padding-right: 10px;
        position: relative;
      }
      & > span:first-child::before {
        content: '';
        display: block;
        width: 1px;
        height: 18px;
        background: $mainColor;
        position: absolute;
        top: 0px;
        left: 35px;
      }
      & > span:last-child {
        color: $mainColor;
      }
    }
    .head-right {
      flex: 1;
      text-align: right;
      color: #3d3c3c;
      & > span {
        cursor: pointer;
      }
    }
  }

 
}
 .plan-content {
    font-size: $fontSize-1;
    display: flex;
    flex-wrap: wrap;
    .one-content {
      display: flex;
      align-items: center;
      padding: 5px 10px 5px 10px;
      box-sizing: border-box;
      width: 50%;
      
      .label {
        padding-right: 10px;
        min-width: 80px;
      }

      .w-180 {
        width: 180px;
      }

      .content-input {
        // width: ;

      }
    }
  }
.btns {
  width: 100%;
  .btn-9 {
    width: 100%;
  }
}

.type-btns {
  display: flex;
  align-items: center;
  & > div {
    padding: 6px 10px;
    border: 1px solid #eee;
    box-sizing: border-box;
    cursor: pointer;
    
  }
}
</style>